//
//  YuYueViewController.m
//  FD
//
//  Created by xiaofang wang on 2018/11/8.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  点击店铺详情跳转到 预约 页面

//2019-2-19保存上次输入内容
#define kYuYueLastTimeInputLianXiRen @"kYuYueLastTimeInputLianXiRen" //联系人
#define kYuYueLastTimeInputSexNumber @"kYuYueLastTimeInputSexNumber" //性别
#define kYuYueLastTimeInputDianHua @"kYuYueLastTimeInputDianHua"   //电话



#import "YuYueViewController.h"
#import "YuYueHeaderView.h"
#import "YuYueFooterView.h" //11-22不要了 12-5要
#import "BRDatePickerView.h"

//controller
#import "YuYueSuccessViewController.h" //预约成功页面

@interface YuYueViewController ()<UITableViewDelegate,UITableViewDataSource>

/**tv*/
@property (nonatomic, strong) UITableView *tv;
/**立即预约按钮*/
@property (nonatomic, strong) UIButton *lijiyuyueBtn;
/**表头 220 */
@property (nonatomic, strong) YuYueHeaderView  *headerView;
/**2.表尾 140*/
@property (nonatomic, strong) YuYueFooterView *footerView;
/**记录选择的时间*/
@property (nonatomic, copy) NSString *selectedTimeStr;
@end

@implementation YuYueViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];
    
//    [self developDefalultValue];
}

- (void)setupView {
    
    //国际化
    NSString *yuyueStr = NSLocalizedString(Home_yuYu, @"预约");
    self.navigationItem.title = yuyueStr;
    
    self.view.backgroundColor = kMainLightGrayColor;
    self.tv.backgroundColor = kMainLightGrayColor;
    
    self.tv.frame =self.view.bounds;
    CGFloat h = 40;
    CGFloat y = SCREEN_HEIGHT - h - FD_TabbarSafeBottomMargin;
    self.lijiyuyueBtn.frame = CGRectMake(0, y, SCREEN_WIDTH, h);
    
    [self.view addSubview:self.tv];
    [self.view addSubview:self.lijiyuyueBtn];
    
    //表头
    self.tv.tableHeaderView = self.headerView;
    self.tv.tableFooterView = self.footerView; //11-22 不要了
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //2019-2-19保存上次输入内容
    FDLog(@"1111:%@",[[NSUserDefaults standardUserDefaults] objectForKey:kYuYueLastTimeInputLianXiRen]);
    self.headerView.lianxirenTF.text = [[NSUserDefaults standardUserDefaults] objectForKey:kYuYueLastTimeInputLianXiRen];
    self.headerView.phoneTf.text = [[NSUserDefaults standardUserDefaults] objectForKey:kYuYueLastTimeInputDianHua];
    
    [self.headerView updateSexWithSexNumber:[[NSUserDefaults standardUserDefaults] objectForKey:kYuYueLastTimeInputSexNumber]];
}


#pragma mark - 二 getter
- (UITableView *)tv {
    if (!_tv) {
        _tv = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)];
        _tv.delegate = self;
        _tv.dataSource = self;
        
        //注册cell
        [_tv registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        //禁止滚动
        _tv.scrollEnabled = NO;
    }
    return _tv;
}

- (YuYueHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[YuYueHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210)];
        
        //2019-2-26 数字键盘
        _headerView.numberTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _headerView;
}
- (YuYueFooterView *)footerView {
    if (!_footerView) {
        _footerView = [[YuYueFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)]; //120-20(现在,xxxx)
        
        FDWeakSelf;
//        NSDate *nowDate = [NSDate date];
//        NSDate *maxDate = [self maxDate];
        //事件回调
        _footerView.footerViewClickYuYueTimeBlock = ^{
            //回收键盘
            [weakSelf.view endEditing:YES];
            
            [BRDatePickerView showDatePickerWithTitle:@"" dateType:(BRDatePickerModeYMDHM) defaultSelValue:@"" resultBlock:^(NSString *selectValue) {
                weakSelf.selectedTimeStr = selectValue;
                [weakSelf.footerView updateYuYueTimestr:selectValue];
            }];
        };
    }
    
    //更新页面。
    
    return _footerView;
}


/**设置最大时间 */
- (NSDate *)maxDate {
    NSString *datestr = @"2020-1-1 23:59";
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    [fmt setDateFormat:@"yyyy-MM-dd HH:ss"];
    
    return [fmt dateFromString:datestr];
}


- (UIButton *)lijiyuyueBtn {
    if (!_lijiyuyueBtn) {
        NSString *str = NSLocalizedString(Home_LiJiYuYue, @"立即预约");
        _lijiyuyueBtn = [UIButton createFastRedBtnRadius:0 target:self action:@selector(clicklijiyuyeBtnAction:) title:str];
    }
    return _lijiyuyueBtn;
}
- (void)clicklijiyuyeBtnAction:(UIButton *)btn {
    [self.view endEditing:YES];

    NSString *num = self.headerView.numberTF.text;
    NSString *name = self.headerView.lianxirenTF.text;
    NSString *phone = self.headerView.phoneTf.text; //
    
    
    //2019-2-22如果有值就直接用,防止sex不存在,服务器返回空指针。
    NSNumber *sex  = self.headerView.sex;
    if ([[NSUserDefaults standardUserDefaults] valueForKey:kYuYueLastTimeInputSexNumber]) {
        sex = [[NSUserDefaults standardUserDefaults] valueForKey:kYuYueLastTimeInputSexNumber];
    }
    
    if ([NSString isEmptyString:num]) {
        [JRToast showWithText:NSLocalizedString(Home_put_your_have_dinner_number, @"请选择用餐人数")];
        return;
    }
    if ([NSString isEmptyString:name]) {
        
        [JRToast showWithText:NSLocalizedString(Home_put_your_contacts_name, @"请输入联系人姓名")];
        return;
    }
    if ([NSString isEmptyString:phone]) {
        [JRToast showWithText:NSLocalizedString(Home_inputPhone, @"请输入联系电话")];
        return;
    }
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"shopId"] = self.shopId;//1.门店编号 Number
    parDic[@"peopleNumber"] = @([num integerValue]); //2.用餐人数 Number
    parDic[@"consignee"] = name; //3.姓名
    parDic[@"sex"] = sex;//4.性别 Number 0:先生 1女士
    parDic[@"phone"] = phone; //5.电话
    
    //这里要坑，要么没有该字段，要么就传一个时间戳
    if (![NSString isEmptyString:self.selectedTimeStr]) {
        
        //坑：选择的是 2018-11-10 11:23 要给服务器传的是 2018-11-10 11:23
        NSString *ymdhmStr = [NSString stringWithFormat:@"%@",self.selectedTimeStr];
        NSNumber *timeStamp = [NSString timeStampnyrsfFromDateStr:ymdhmStr];
        
        parDic[@"diningTime"] = timeStamp; //用餐时间  13位时间戳 Number
    }
    
    //2019-2-19保存用户输入的内容
    [[NSUserDefaults standardUserDefaults] setValue:name forKey:kYuYueLastTimeInputLianXiRen];
    [[NSUserDefaults standardUserDefaults] setValue:phone forKey:kYuYueLastTimeInputDianHua];
    [[NSUserDefaults standardUserDefaults] setValue:sex forKey:kYuYueLastTimeInputSexNumber];
    
    
    [self requestLijiYuYuePardic:parDic btn:btn];
}

//!!!!:网络请求 防止连续点击
- (void)requestLijiYuYuePardic:(NSDictionary *)pardic btn:(UIButton *)btn{
    btn.enabled = NO; //禁止点击🚫
    [FDHttpAPi requestUserLiJiYuyuePardic:pardic successBlock:^(id responseObjc) {
        btn.enabled = YES; //允许点击✅
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            
            //跳转预约成功页面
            YuYueSuccessViewController *successVC = [[YuYueSuccessViewController alloc] initWithNibName:@"YuYueSuccessViewController" bundle:nil];
            
            successVC.successDic = responseObjc[@"data"]; //将字典传过去
            [self.navigationController pushViewController:successVC animated:YES];
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
        btn.enabled = YES; //允许点击✅
    }];
}

#pragma mark - 三 代理 UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.textLabel.text = [NSString stringWithFormat:@"%ld--%ld",indexPath.section,indexPath.row];
    return cell;
}

#pragma mark - 四

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


//!!!!:开发节约时间提前把数据写好
- (void)developDefalultValue {

    self.headerView.numberTF.text = @"2";
    
    NSArray *titleArr = @[@"张学友",@"刘德华",@"谢霆锋",@"古天乐",@"程咬金",@"赵子龙"];
    
    int randomIndex = arc4random() % titleArr.count;
    self.headerView.lianxirenTF.text = titleArr[randomIndex];
    self.headerView.phoneTf.text = @"158267954";
}

@end
